# -*- coding: utf-8 -*-
# @Date    : 2015-06-21 15:50:35
# @Author  : Your Name (you@example.org)
# @Link    : http://example.org
# @Version : $Id$


from lib.tornado_routes import route
from web.handler import BaseHandler
from tornado import gen
from tornado.web import asynchronous
from web.models.admin.user.student import Student
from decorator.auth import admin_login_required, admin_auth
import json
import time
import md5
import base64
from lib import libupload


@route(r'/admin/user/student/?', name='student.index')
class IndexHandler(BaseHandler):

    @asynchronous
    @gen.coroutine
    # @admin_auth
    def get(self):
        cur_page = self.get_argument('page', default=1)
        school_id = self.get_argument('schoolId', default=self.school_id)

        school = self.get_cookie('school', base64.b16encode('{}'))
        school = json.loads(base64.b16decode(school))
        dt = school.get('student', {})
        sname = dt.get('sname', '')
        sno = dt.get('sno', '')
        sdorm = dt.get('sdorm', '')
        sstatus = dt.get('sstatus', '')

        where = {
            "Fname":   sname,
            "Fno":     sno,
            "Fdorm_id": sdorm,
            "Fstatus": sstatus,
        }

        page = (int(cur_page) - 1) * self.offset

        drom = yield Student().select_dorm(school_id)
        ret, count = yield Student().select_student(school_id, where, page, self.offset)

        page_info = {'total': count, 'page': int(cur_page)}
        self.render(
            "admin/user/student/list.html", data=ret, page_info=page_info, drom=drom, where=where)

    def post(self):
        cur_page = self.get_argument('page', default='1')
        school_id = self.get_argument('schoolId', default=self.school_id)
        sname = self.get_argument('sname', default='')
        sno = self.get_argument('sno', default='')
        sdorm = self.get_argument('sdorm', default='-1')
        sstatus = self.get_argument('sstatus', default='-1')

        school = self.get_cookie('school', base64.b16encode('{}'))
        school = json.loads(base64.b16decode(school))
        dt = school.get('student', {})

        if sname != '':
            dt['sname'] = sname
        else:
            dt.pop('sname', '')

        if sno != '':
            dt['sno'] = sno
        else:
            dt.pop('sno', '')

        if sdorm != '-1':
            dt['sdorm'] = sdorm
        else:
            dt.pop('sdorm', '')

        if sstatus != '-1':
            dt['sstatus'] = sstatus
        else:
            dt.pop('sstatus', '')

        school["student"] = dt
        self.set_cookie('school', base64.b16encode(json.dumps(school)))

        self.redirect('/admin/user/student/')


@route(r'/admin/user/student/new/?', name='student.new')
class NewHandler(BaseHandler):

    @asynchronous
    @gen.coroutine
    def get(self):
        school_id = self.get_argument('schoolId', default=self.school_id)

        room = []
        drom = yield Student().select_dorm(school_id)
        school = yield Student().select_school(school_id)
        if len(drom) >= 1:
            room = yield Student().select_room(school_id, drom[0]["Fid"])

        self.render(
            "admin/user/student/new.html", drom=drom, room=room, school=school)

    @asynchronous
    @gen.coroutine
    def post(self):
        ltype = self.get_argument('ltype', default='0')
        school_id = self.get_argument('schoolId', default=self.school_id)
        Ftel = self.get_argument('Ftel', default='')
        Froom = self.get_argument('Froom', default='')
        Fname = self.get_argument('Fname', default='')
        Fusername = self.get_argument('Fusername', default='')
        Fno = self.get_argument('Fno', default='')
        Fdorm_id = self.get_argument('Fdorm_id', default='')
        Fage = self.get_argument('Fage', default='')
        Fpasswd = self.get_argument('Fpasswd', default='')
        Fstatus = self.get_argument('Fstatus', default='0')
        Fmajor_id = self.get_argument('Fmajor_id', default='')
        Favatar = self.request.files.get('Favatar')

        if Favatar is not None:
            Favatar, path = libupload.save(Favatar[0])
            libupload.img.thumbnail(path, path, 100, 100)
        else:
            Favatar = ""


        student_data = {
            "Fuser_name":   Fusername,
            "Fpwd":         md5.md5(Fpasswd).hexdigest(),
            "Ftype":        1,
            "Fuser_id":     0,
            "Fcreate_time": time.time(),
        }

        student_info_data = {
            "Fname":         Fname,
            "Fno":           Fno,
            "Fdorm_id":      Fdorm_id,
            "Froom":         Froom,
            "Ftel":          Ftel,
            "Fage":          Fage,
            "Fschool_id":    school_id,
            "Fmajor_id":     Fmajor_id,
            "Fstatus":       Fstatus,
            "Fcreate_time":  time.time(),
            "Favatar":       Favatar
        }

        count = yield Student().insert_student(student_data, student_info_data)

        if ltype == '0':
            self.redirect('/admin/user/student/')
        else:
            self.redirect('/admin/user/student/new/')
        # self.xhr_redirect('post','/admin/base/result')
        # self.xhr_success('suc')


@route(r'/admin/user/student/edit/(?P<Fid>[0-9].*)', name='student.edit')
class EditHandler(BaseHandler):

    @asynchronous
    @gen.coroutine
    def get(self, Fid):
        school_id = self.get_argument('schoolId', default=self.school_id)

        student = yield Student().find_student(Fid)
        room = []
        drom = yield Student().select_dorm(school_id)
        school = yield Student().select_school(school_id)
        if len(drom) >= 1:
            room = yield Student().select_room(school_id, drom[0]["Fid"])

        self.render(
            "admin/user/student/edit.html", drom=drom, room=room, school=school, student=student)

    @asynchronous
    @gen.coroutine
    def post(self, Fid):
        school_id = self.get_argument('schoolId', default=self.school_id)
        Ftel = self.get_argument('Ftel', default='')
        Froom = self.get_argument('Froom', default='0')
        Fname = self.get_argument('Fname', default='')
        Fusername = self.get_argument('Fusername', default='')
        Fno = self.get_argument('Fno', default='')
        Fdorm_id = self.get_argument('Fdorm_id', default='0')
        Fage = self.get_argument('Fage', default='')
        Fpasswd = self.get_argument('Fpasswd', default='')
        Fstatus = self.get_argument('Fstatus', default='0')
        Fmajor_id = self.get_argument('Fmajor_id', default='0')
        Favatar = self.request.files.get('Favatar')

        if Favatar is not None:
            Favatar, path = libupload.save(Favatar[0])
            libupload.img.thumbnail(path, path, 100, 100)
        else:
            Favatar = ""

        student_info_data = {
            "Fname":         Fname,
            "Fno":           Fno,
            "Fdorm_id":      Fdorm_id,
            "Froom":         Froom,
            "Ftel":          Ftel,
            "Fage":          Fage,
            "Fschool_id":    school_id,
            "Fmajor_id":     Fmajor_id,
        }
        if Favatar != "":
            student_info_data['Favatar'] = Favatar

        count = yield Student().update_student(Fid, Fusername, student_info_data)

        self.redirect('/admin/user/student/')
        # self.xhr_redirect('post','/admin/base/result')
        # self.xhr_success('suc')


@route(r'/admin/user/student/del/(?P<FstudentId>[0-9].*)/(?P<cur_page>[0-9].*)', name='student.del_student')
class DelHandler(BaseHandler):

    @asynchronous
    @gen.coroutine
    def get(self, FstudentId, cur_page):
        school_id = self.get_argument('schoolId', default=self.school_id)

        ret = Student().del_student(FstudentId)

        self.redirect('/admin/user/student/?page=' + cur_page)


@route(r'/admin/user/student/istatus/(?P<cur_page>[0-9].*)/(?P<Fstatus>[0-9].*)', name='student.set_istatus')
class IstatusHandler(BaseHandler):

    @asynchronous
    @gen.coroutine
    def post(self, cur_page, Fstatus):
        school_id = self.get_argument('schoolId', default=self.school_id)
        data = self.get_argument('data', default='')

        ret = yield Student().set_istatus(Fstatus, *(data.split(',')))

        self.write(str(ret))

        # self.redirect('/admin/user/student/?page=' + cur_page)


@route(r'/admin/user/student/status/(?P<Fid>[0-9].*)/(?P<Fstatus>[0-9].*)/(?P<cur_page>[0-9].*)', name='student.set_status')
class StatusHandler(BaseHandler):

    @asynchronous
    @gen.coroutine
    def get(self, Fid, Fstatus, cur_page):
        school_id = self.get_argument('schoolId', default=self.school_id)

        ret = yield Student().set_status(Fid, Fstatus)

        self.redirect('/admin/user/student/?page=' + cur_page)


@route(r'/admin/user/student/get_room/(?P<drom_id>[0-9].*)', name='student.get_room')
class GetRoomHandler(BaseHandler):

    @asynchronous
    @gen.coroutine
    def get(self, drom_id):
        school_id = self.get_argument('schoolId', default=self.school_id)

        room = yield Student().select_room(drom_id, school_id)

        self.write(json.dumps(room))


@route(r'/admin/user/student/new_result/?', name='student.new_result')
class ResultHandler(BaseHandler):

    def get(self):
        print self.get_argument('param', default=1)
        self.write('asdfsadf')
